package com.volunteer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.volunteer.common.Result;
import com.volunteer.entity.Activity;
import com.volunteer.entity.ActivityEnrollment;
import com.volunteer.service.ActivityService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 活动控制器
 */
@RestController
@RequestMapping("/api/activities")
@RequiredArgsConstructor
public class ActivityController {

    private final ActivityService activityService;

    /**
     * 分页查询活动列表
     */
    @GetMapping
    public Result<IPage<Activity>> getActivityList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String category) {
        IPage<Activity> result = activityService.getActivityList(page, size, status, category);
        return Result.success(result);
    }

    /**
     * 获取活动详情
     */
    @GetMapping("/{id}")
    public Result<Activity> getActivityById(@PathVariable Long id) {
        Activity activity = activityService.getActivityById(id);
        return Result.success(activity);
    }

    /**
     * 创建活动（管理员）
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Activity> createActivity(@RequestBody Activity activity) {
        Activity created = activityService.createActivity(activity);
        return Result.success("创建成功", created);
    }

    /**
     * 更新活动（管理员）
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> updateActivity(@PathVariable Long id, @RequestBody Activity activity) {
        activity.setId(id);
        activityService.updateActivity(activity);
        return Result.success("更新成功", null);
    }

    /**
     * 删除活动（管理员）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> deleteActivity(@PathVariable Long id) {
        activityService.deleteActivity(id);
        return Result.success("删除成功", null);
    }

    /**
     * 报名活动
     */
    @PostMapping("/{id}/enroll")
    public Result<Void> enrollActivity(
            @PathVariable Long id,
            @RequestBody Map<String, Object> request) {
        Long userId = Long.parseLong(request.get("userId").toString());
        String reason = request.getOrDefault("reason", "").toString();
        activityService.enrollActivity(id, userId, reason);
        return Result.success("报名成功", null);
    }

    /**
     * 取消报名
     */
    @PostMapping("/{id}/cancel")
    public Result<Void> cancelEnrollment(
            @PathVariable Long id,
            @RequestBody Map<String, Object> request) {
        Long userId = Long.parseLong(request.get("userId").toString());
        String cancelReason = request.getOrDefault("cancelReason", "").toString();
        activityService.cancelEnrollment(id, userId, cancelReason);
        return Result.success("取消成功", null);
    }

    /**
     * 签到
     */
    @PostMapping("/{id}/checkin")
    public Result<Void> checkIn(
            @PathVariable Long id,
            @RequestBody Map<String, Object> request) {
        Long userId = Long.parseLong(request.get("userId").toString());
        activityService.checkIn(id, userId);
        return Result.success("签到成功", null);
    }

    /**
     * 签退
     */
    @PostMapping("/{id}/checkout")
    public Result<Void> checkOut(
            @PathVariable Long id,
            @RequestBody Map<String, Object> request) {
        Long userId = Long.parseLong(request.get("userId").toString());
        activityService.checkOut(id, userId);
        return Result.success("签退成功", null);
    }

    /**
     * 检查未签退记录（管理员）
     */
    @PostMapping("/{id}/check-missing-checkout")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> checkMissingCheckOut(@PathVariable Long id) {
        activityService.checkMissingCheckOut(id);
        return Result.success("检查完成", null);
    }

    /**
     * 完成活动并结算积分（管理员）
     */
    @PostMapping("/{id}/complete")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> completeActivity(@PathVariable Long id) {
        activityService.completeActivity(id);
        return Result.success("活动已完成，积分已发放", null);
    }

    /**
     * 获取用户的报名记录
     */
    @GetMapping("/user/{userId}/enrollments")
    public Result<List<ActivityEnrollment>> getUserEnrollments(@PathVariable Long userId) {
        List<ActivityEnrollment> enrollments = activityService.getUserEnrollments(userId);
        return Result.success(enrollments);
    }

    /**
     * 获取活动的报名列表（管理员）
     */
    @GetMapping("/{id}/enrollments")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<ActivityEnrollment>> getActivityEnrollments(@PathVariable Long id) {
        List<ActivityEnrollment> enrollments = activityService.getActivityEnrollments(id);
        return Result.success(enrollments);
    }

    /**
     * 审核报名（管理员）
     */
    @PutMapping("/enrollments/{enrollmentId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> approveEnrollment(
            @PathVariable Long enrollmentId,
            @RequestBody Map<String, String> request) {
        String status = request.get("status");
        activityService.approveEnrollment(enrollmentId, status);
        return Result.success("审核成功", null);
    }
}

